package com.cmnit.tools.utils;

import java.io.*;
import java.util.List;

public class IOUtils {
    /**
     * 将文件读入到一个String，利用FileReader+BufferedReader(提供readLine方法)
     *
     * @param fileName
     * @return String
     */
    public static String fileReaderStringHandle(String fileName) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(new FileReader(new File(fileName).getAbsoluteFile()));
            String str;
            while ((str = in.readLine()) != null) {
                sb.append(str);
                sb.append("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

    /**
     * 使用FileInputStream+BufferedInputStream以byte的方式处理文件
     *
     * @param fileName
     * @return byte[]
     */
    public static byte[] fileReaderByteHandle(String fileName) {
        byte[] data;
        try {
            BufferedInputStream bf = new BufferedInputStream(new FileInputStream(fileName));
            data = new byte[bf.available()];
            bf.read(data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return data;
    }

    /**
     * 将指定的字符集合写入到文件名为fileName的文件中
     *
     * @param fileName
     * @param list
     * @param isAppend
     */
    public static void fileWriterHandle(String fileName, List<String> list, Boolean isAppend) {
        try (PrintWriter out = new PrintWriter(new FileWriter(fileName, isAppend))) {
            for (String s : list) {
                out.println(s);
            }
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
